<!-- 首页 -->
<script>
import SubtitledSection from '@/components/layout/SubtitledSection.vue'
import SubtitledSectionLong from '@/components/layout/SubtitledSectionLong.vue'
import Head2 from '@/components/layout/Head2.vue'
import DeviceList from '@/components/layout/DeviceList.vue'
import AlarmList from '@/components/layout/AlarmList.vue'
import {caicon, select_equipmentv2, shebeilistv2, getcamera,getweather } from '@/request/api';
import chartline from '@/components/charts/Line/Line.vue'
import axios from 'axios';
import EZUIKit from 'ezuikit-js';

export default {
  components: {
    SubtitledSection, //短标题框
    SubtitledSectionLong,//长标题框
    Head2,//头部
    DeviceList,
    AlarmList,
    chartline
  },
  data() {
    return {
      videoAddresses: [],
      SerialNumber: [],
      video_address: [],
      cameralist: [],
      base_id: "",
      shelist: [],
      jktokens: {
        value: ''
      },
      formattedData: [
        { label: '设备名称', value: '' },
        { label: '设备描述', value: '' },
        { label: '运行状态', value: '' },
        { label: '电压', value: '' },
        { label: '光照', value: '' },
        { label: '风速', value: '' },
        { label: '风向', value: '' },
        { label: '辐射', value: '' },
        { label: 'ORP', value: '' },
        { label: 'CON', value: '' },
      ],
      currentTime: '',
      miaoshu: { EQUIPMENT_NAME: '', INTRODUCE: '', Online_Voltage: '', state: '', LIGHT: '', WIND_SPEED: '', WIND_DIRECTION: '', RADIATION: '', ORP: '', CON: '', type: 1 },
      box: 0,
      zuobiaolist: [],
      shebeilist: {
        "water": [],
        "meteorological": [],
        "monitoring": []
      },
      equipmentID: '',
      lineData: [
        {
          name: "温度",
          data: [],
          xAxisData: [],
          data1: [],
          data2: [],
        }, {
          name: "溶氧值",
          data: [],
          xAxisData: [],
          data1: [],
          data2: [],
        }, {
          name: "PH",
          data: [],
          xAxisData: [],
          data1: [],
          data2: [],
        }, {
          name: "雨量",
          data: [],
          xAxisData: [],
          data1: [],
          data2: [],
        }
      ],
      videoSrc1: '',
      videoSrc2: '',
      // wetherinfo: {
      //   'wendu': {
      //     img: 'top-info-wd.png',
      //     value: '0'
      //   },
      //   'shidu': {
      //     img: 'top-info-xy.png',
      //     value: '0'
      //   },
      //   'fengxiang': {
      //     img: 'top-info-ql.png',
      //     value: '0'
      //   },
      //   'fengsu': {
      //     img: 'top-info-fs.png',
      //     value: '0'
      //   },
      //   'guangzhao': {
      //     img: 'top-info-yg.png',
      //     value: '0'
      //   },
      //   'jiangyuliang': {
      //     img: 'top-info-sd.png',
      //     value: '0'
      //   },
      //   'qiya': {
      //     img: 'top-info-qy.png',
      //     value: '0'
      //   }
      // },
      wetherinfo1: {
        'temperature': {
          img: 'top-info-wd.png',
          value: '0'
        },
        'humidity': {
          img: 'top-info-xy.png',
          value: '0'
        },
        'wind_direction': {
          img: 'top-info-ql.png',
          value: '0'
        },
        'wind_power': {
          img: 'top-info-fs.png',
          value: '0'
        }, 
        'guangzhao': {
          img: 'top-info-yg.png',
          value: '-'
        },
        'precipitation': {
          img: 'top-info-sd.png',
          value: '-'
        },
        'pressure': {
          img: 'top-info-qy.png',
          value: '-'
        } ,
      },
      selectid: 0,
      alertYuanList: [],
      TEM: 0,
      PH: 0,
      O2: 0,
      SALT: 0,
      CON: 0,
      HUMIDITY: 0,
      ATM: 0,
      RAINFALL: 0,
      markerBackgrounds: {
        '水质检测': require('@/assets/ui/position-text-bg.png'),
        '气象检测': require('@/assets/ui/position-text-bg2.png')
      },
      city: '上海',  // 直接设置城市为 "上海"
      livetianqi: null,  // 存储天气数据
    }
  },
  computed: {
    backgroundImage() {
      if (this.miaoshu.EQUIPMENT_TYPE === "水质检测") {
        return require('@/assets/ui/map-bg1.png');
      } else {
        return require('@/assets/ui/map-bg2.png');
      }
    },
    labelcolor() {
      return this.miaoshu.EQUIPMENT_TYPE == "水质检测" ? '#5CA0B1' : '#99BB6D'
    },
    valuecolor() {
      return this.miaoshu.EQUIPMENT_TYPE == "水质检测" ? '#c6e1e7' : '#e9f6d8'
    },
    miaoshuFormatted() {
      if (this.miaoshu.EQUIPMENT_TYPE == "水质检测") {
        const formattedData = [
          { label: '设备名称', value: this.miaoshu.EQUIPMENT_NAME },
          { label: '采集时间', value: this.miaoshu.ACQUISITION_TIME },
          { label: '设备描述', value: this.miaoshu.INTRODUCE },
          { label: '电压', value: this.miaoshu.VOLTAGE },
          { label: '状态', value: this.miaoshu.state },
          { label: 'ORP', value: this.miaoshu.ORP },
          { label: '电导', value: this.miaoshu.CON },
          { label: '温度', value: this.miaoshu.TEM },
          { label: 'PH', value: this.miaoshu.PH },
          { label: '含氧量', value: this.miaoshu.O2 },
          { label: '盐度', value: this.miaoshu.SALT }
        ];
        return formattedData;
      }
      else if (this.miaoshu.EQUIPMENT_TYPE == "气象检测") {
        const formattedData = [
          { label: '设备名称', value: this.miaoshu.EQUIPMENT_NAME },
          { label: '采集时间', value: this.miaoshu.ACQUISITION_TIME },
          { label: '设备描述', value: this.miaoshu.INTRODUCE },
          { label: '电压', value: this.miaoshu.VOLTAGE },
          { label: '状态', value: this.miaoshu.state },
          { label: '光照', value: this.miaoshu.LIGHT },
          { label: '风速', value: this.miaoshu.WIND_SPEED },
          { label: '风向', value: this.miaoshu.WIND_DIRECTION },
          { label: '辐射', value: this.miaoshu.RADIATION },
          { label: '温度', value: this.miaoshu.TEM },
          { label: '湿度', value: this.miaoshu.HUMIDITY }
          // { label: '气压', value: this.miaoshu.ATM },
          // { label: '雨量', value: this.miaoshu.RAINFALL }
        ];
        return formattedData;
      }
      return [];
    },
  },
  mounted() {
    this.renderMap();
    this.GetCamera();
    this.getlist();
    // this.startPolling(); // 开始定时请求数据
    this.getToken();
    this.GetWeather();

  },
  methods: {
    startPolling() {
      this.intervalId = setInterval(() => {
        // this.getlist();
      }, 60000); // 每60秒（1分钟）调用一次getlist
    },
    addAlarm(message, value, type, time) {
      this.alertYuanList.push({
        message,
        value,
        type,
        time,
      });
    },
    getCurrentTime() {
      const now = new Date();
      return `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
    },

    handleLinkShebei(type, item, index) {
      if (type == "water") {
        this.selectid = 1
      } else if (type == "meteorological") {
        this.selectid = 2
      } else if (type == "monitoring") {
        this.selectid = 1
      }
      if (type !== "monitoring") {
        // 查找对应的坐标
        // console.log("item", item);
        if (item.ACQUISITION_TIME) {
          this.currentTime = item.ACQUISITION_TIME.replace('T', ' ');
        }
        this.selectEquipment(item, 1)
        const selectedCoordinate = this.zuobiaolist.find(coord =>
          coord.toString() === item.EQUIPMENT_LOCATION
        );

        if (selectedCoordinate) {
          // 如果找到对应的坐标，将地图中心设置为该坐标
          this.map.setCenter(selectedCoordinate);

          // 可选：调整缩放级别
          this.map.setZoom(18);

          // 可选：添加动画效果
          this.map.panTo(selectedCoordinate);
        }

        // 更新 miaoshu 数据
        this.miaoshu = item;
        this.miaoshu.state = item.STATE == 0 ? "停止" : "正常";
        this.miaoshu.type = type == "water" ? 1 : 2;
        // // 调用 addEquipment 方法（如果需要的话）
        //   this.addEquipment(type == "water" ? 0 : 1);
        // 在这里处理点击事件
        this.getshebeidata(item);
      }
      else{
        if (index % 2 == 0) {
          this.initPlayer(item.video_address, item.serial_number);
        }
        else {
          this.initPlayer1(item.video_address, item.serial_number);
        }

        if (item.camera_location) {
          const position = item.camera_location.split(',');
          if (position) {
            // 设置地图中心点
            this.map.setCenter(position);
            this.map.setZoom(18);
            this.map.panTo(position);
          }
          // 不直接播放视频，等待用户点击地图上的标记
          return;
        }
      }

      // 您可以在这里添加您原来在 linkshebei 方法中的逻辑
    },
    getshebeidata(item) {
      select_equipmentv2({
        base_id: this.$route.query.base_id,
        equipmentID: item.ID
      }).then(res => {
        const data = res.data.shuju
        this.lineData = []

        this.lineData = [
          {
            name: "温度",
            id: 1,
            data: data.templist[0].y[0].data,
            xAxisData: data.templist[0].x,
            data1: data.templist[0].y[1].data,
            data2: data.templist[0].y[2].data,
            max: data.templist[0].max,
            min: data.templist[0].min,
          }
        ]  
        if (this.selectid == 1) {
          this.lineData.push(
            {
              name: "PH",
              id: 2,
              data: data.templist[2].y[0].data,
              xAxisData: data.templist[0].x,
              data1: data.templist[2].y[1].data,
              data2: data.templist[2].y[2].data,
              max: data.templist[2].max,
              min: data.templist[2].min,
            }, {
            name: "溶氧值",
            id: 3,
            data: data.templist[1].y[0].data,
            xAxisData: data.templist[0].x,
            data1: data.templist[1].y[1].data,
            data2: data.templist[1].y[2].data,
            max: data.templist[1].max,
            min: data.templist[1].min,
          }
          )
        }
        else if (this.selectid == 2) {
          if (data.templist && data.templist.length > 0){
            this.lineData.push(
            {
              name: "溶氧值",
              id: 2,
              data: data.templist[3].y[0].data,
              xAxisData: data.templist[0].x,
              data1: data.templist[3].y[1].data,
              data2: data.templist[3].y[2].data,
              max: data.templist[3].max,
              min: data.templist[3].min,
            }, {
            name: "PH",
            id: 3,
            data: data.templist[4].y[0].data,
            xAxisData: data.templist[0].x,
            data1: data.templist[4].y[1].data,
            data2: data.templist[4].y[2].data,
            max: data.templist[4].max,
            min: data.templist[4].min,
          }, {
            name: "雨量",
            id: 4,
            data: data.templist[5].y[0].data,
            xAxisData: data.templist[0].x,
            data1: data.templist[5].y[1].data,
            data2: data.templist[5].y[2].data,
            max: data.templist[5].max,
            min: data.templist[5].min,
          })}
          else {
        // 如果数据为空，重置 selectid 为 1
        this.selectid = 1;
        this.lineData = []; // 清空数据
        }
        }
      })
    },
    getlist() {
      this.base_id = this.$route.query.base_id
      shebeilistv2({
        base_id: this.base_id,
      }).then(res => {
        console.log('数据接口:', res);
        this.getshebeidata(res.data.shebeilist[0]);
        console.log("res",res);
        // let tianqi = res.data.tianqi;
        // Object.keys(tianqi).forEach(key => {
        //   if (Object.prototype.hasOwnProperty.call(this.wetherinfo, key)) {
        //     this.wetherinfo[key].value = parseFloat(parseFloat(tianqi[key]).toFixed(1));
        //   }
        // });
        this.shelist = res.data.shebeilist;
        this.shelist.map(item => {
          item.UANDL = JSON.parse(item.UANDL)
          if (item.EQUIPMENT_TYPE == '水质检测') {
            this.shebeilist.water.push(item)
          } else if (item.EQUIPMENT_TYPE == '气象检测') {
            this.shebeilist.meteorological.push(item)
          } else if (item.EQUIPMENT_TYPE == '监控检测') {
            this.shebeilist.monitoring.push(item)
          }
        })
        for (let i = 1; i < this.shelist.length; i++) {
          const device = this.shelist[i];
          const Online_Voltage = device.Online_Voltage;
          // 检查设备类型是否为水质设备
          if (device.EQUIPMENT_TYPE === '水质检测') {
            const oxygenLevel = device.O2;
            const temperature = device.TEM;
            const pHValue = device.PH;
            const UANDL = device.UANDL;
            const time = device.ACQUISITION_TIME;

            let parsedUANDL = UANDL;
            if (typeof UANDL === 'string') {
              try {
                parsedUANDL = JSON.parse(UANDL);
              } catch (error) {
                console.error('解析 UANDL 失败:', error);
              }
            } else if (typeof UANDL !== 'object' || UANDL === null) {
              console.error('UANDL 不是有效的对象或 JSON 字符串');
              return; // 或者进行其他错误处理
            }
            if (oxygenLevel < parsedUANDL.o2.th[0] || oxygenLevel > parsedUANDL.o2.th[1]) {
              const alarmMessage = `${device.EQUIPMENT_NAME}的溶氧值异常`;
              const value = oxygenLevel
              this.addAlarm(alarmMessage, value, 1, time);
            }
            if (temperature < parsedUANDL.te.th[0] || temperature > parsedUANDL.te.th[1]) {
              const alarmMessage = `${device.EQUIPMENT_NAME}的温度异常`;
              const value = temperature
              this.addAlarm(alarmMessage, value, 1, time);
            }

            if (pHValue < parsedUANDL.ph.th[0] || pHValue > parsedUANDL.ph.th[1]) {
              const alarmMessage = `${device.EQUIPMENT_NAME}的PH值异常`;
              const value = pHValue
              this.addAlarm(alarmMessage, value, 1, time);
            }
            if (Online_Voltage == 0 || Online_Voltage < 10) {
              const alarmMessage = `${device.EQUIPMENT_NAME}的电压值异常`;
              const value = Online_Voltage
              this.addAlarm(alarmMessage, value, 2, time);
            }
          }
        }
        this.zuobiaolist = res.data.zuobiaoilist;
        this.inforlist = res.data.inforlist;
        this.alertlist = res.data.alertlist;
        // this.tianqi = res.data.tianqi;
        this.chuangan2 = res.data.chuangan2; //所有设备的传感器参数（最新的一条）
        this.chuangan = res.data.chuangan;  //传感器传来的设备一参数,用来初始化

        // this.PH = res.data.shebeilist[0].PH
        // this.TEM = res.data.shebeilist[0].TEM //初始温度
        // this.O2 = res.data.shebeilist[0].O2
        // this.SALT = res.data.shebeilist[0].SALT
        // this.CON = res.data.shebeilist[0].CON

        // this.shebeiname="设备参数  " +  this.chuangan.EQUIPMENT_NAME

        // this.shuju = res.data.shuju;
        this.shuju2 = res.data.shuju2;
        this.aa = this.shuju2.templist[0];//默认折线图、设备一参数 
        this.renderMap();
        this.handleLinkShebei('water', { ID: 1 })
        this.selectEquipment(this.shelist[0], 1) //默认选择第一个设备展示
      })
    },
    selectEquipment(i, index) {
      if (i.ACQUISITION_TIME) {
        this.currentTime = i.ACQUISITION_TIME.replace('T', ' ');
      }
      this.equipmentID = i.ID
      if (i.EQUIPMENT_TYPE == '水质检测') {
        this.weatherData = false;
        this.waterData = true;
        this.shebeiname = "设备参数  " + i.EQUIPMENT_NAME;
        this.PH = i.PH
        this.TEM = i.TEM
        this.O2 = i.O2
        this.SALT = i.SALT
        this.CON = i.CON
        this.aa = ''
      } else if (i.EQUIPMENT_TYPE == '气象检测') {
        this.weatherData = true;
        this.waterData = false;
        this.shebeiname = "设备参数  " + i.EQUIPMENT_NAME;
        this.HUMIDITY = i.HUMIDITY
        this.TEM = i.TEM
        this.RAINFALL = i.RAINFALL
        this.ATM = i.ATM
        this.aa = ''
      }
      //  点击设备设置中心位置
      for (this.zuoBiaoProp of this.zuobiaolist) {
        this.X = this.zuoBiaoProp[0];
        this.Y = this.zuoBiaoProp[1];
        const zuoBiaoStr = this.zuoBiaoProp.toString();
        if (zuoBiaoStr == i.EQUIPMENT_LOCATION) {
          this.map.setCenter([this.zuoBiaoProp[0], this.zuoBiaoProp[1]]);
        }
      }
    },
    addEquipment(ty) {
      console.log("this.equipmentID", this.equipmentID);
      select_equipmentv2({
        base_id: this.$route.query.base_id,
        equipmentID: this.equipmentID
      }).then(res => {
        this.shuju = res.data.shuju;
        this.aa = this.shuju.templist[this.active];
      })
    },
    renderMap() {
      this.$AMapLoader.load({
        key: 'bb41d02b6376f70646e2490b6bf5f80b',
        version: '1.4.15',
        plugins: ['AMap.MapType'], // 添加 MapType 插件
        AMapUI: {
          version: '1.1',
          plugins: []
        },
        Loca: {
          version: '1.3.2'
        }
      }).then((AMap) => {
        this.map = new AMap.Map('map-container', {
          layers: [new AMap.TileLayer.Satellite(), new AMap.TileLayer.RoadNet()],
          zoom: 18,
          center: this.zuobiaolist[0]
        });
        
        // 添加地图类型切换控件
        this.map.addControl(new AMap.MapType({
          defaultType: 1 // 0代表默认地图，1代表卫星地图
        }));
        // this.map.addControl(new AMap.MapType({
        //   defaultType: 1//0代表默认，1代表卫星
        // }));
        const list = this.zuobiaolist;
        let cursor = 'pointer'; // 默认鼠标样式
        async function ca_icon(local, base_id) {
          let icon = '';
          await caicon({ zuobiao: local, base_id: base_id }).then(res => {
            if (res && res.data == "水质检测") {
              // if (res && res.data.EQUIPMENT_TYPE == "水质检测") {
              icon = new AMap.Icon({
                size: new AMap.Size(40, 40), // 图标尺寸
                cursor,
                // image: require('@/assets/img/location.svg'), // Icon的图像
                image: require('@/assets/ui/map-icon1.png'), // Icon的图像
                imageSize: new AMap.Size(40, 40) // 根据所设置的大小拉伸或压缩图片
              });
            } else {
              icon = new AMap.Icon({
                size: new AMap.Size(40, 40), // 图标尺寸
                image: require('@/assets/ui/map-icon2.png'),
                cursor,
                // Icon的图像
                // image: require('@/assets/img/shexiangtou.svg'), // Icon的图像
                imageSize: new AMap.Size(40, 40), // 根据所设置的大小拉伸或压缩图片
              });
            }

          })
          return icon;
        }
        const shelist = this.shelist
        list.forEach(async (item, index) => { //坐标循环，以列表的形式赋值给item
          let icon = await ca_icon(item, this.base_id)
          let equipmentType = await this.getEquipmentType(item, this.base_id)

          const marker = new AMap.Marker({
            position: item,
            offset: new AMap.Pixel(-20, -25), // 偏移值
            icon,
            label: {
              content: `<div class="custom-label-${index}" style="  padding: 10px;margin:0px 0 0 40px">${shelist[index].EQUIPMENT_NAME}</div>`,
              //offset: new AMap.Pixel(27, 25)

            },
          })
          this.$nextTick(() => {
            this.setCustomLabelStyle(marker, equipmentType, index);
          });
          marker.on('click', () => {
            this.box = 1
            this.map.setCenter([item[0], item[1]]);
            const zuobiaopinStr = item.toString()
            for (this.abc of this.shelist) {
              if (zuobiaopinStr == this.abc.EQUIPMENT_LOCATION) {  //判断地图点坐标与设备列表坐标，确定设备号
                // 设备描述
                var MOB = (this.abc.MOBILITY > 0) ? "可移动" : "不可移动"
                var state = (this.abc.STATE == 0) ? "停止" : "正常"
                this.miaoshu = this.abc

                // this.miaoshu = "设备名称:" + this.abc.EQUIPMENT_NAME + "\n\n设备描述：" + this.abc.INTRODUCE + "\n\n电压:" + this.abc.Online_Voltage + "\n\n运行状态：" + state + "\n\n移动性：" + MOB
                if (this.abc.EQUIPMENT_TYPE == '水质检测') {
                  this.miaoshu.state = state
                  this.miaoshu.type = 1
                  this.addEquipment(0)
                }
                if (this.abc.EQUIPMENT_TYPE == '气象检测') {
                  this.miaoshu.type = 2

                  this.addEquipment(1)
                  //温度，湿度，气压，雨量

                }
              }
            }

          })
          this.map.add(marker);

        })


        if (this.cameralist && this.cameralist.length > 0) {
          this.cameralist.forEach((camera, index) => {
            if (camera.camera_location) {
              const position = camera.camera_location.split(',');
              const marker = new AMap.Marker({
                position: position,
                offset: new AMap.Pixel(-20, -25),
                icon: new AMap.Icon({
                  size: new AMap.Size(40, 40),
                  image: require('@/assets/ui/map-icon3.png'), // 请确保有摄像头图标
                  imageSize: new AMap.Size(40, 40)
                }),
                label: {
                  content: `<div class="camera-label" style="padding: 10px; margin:0px 0 0 40px">${camera.camera_name}</div>`,
                }
              });

              // 添加点击事件
              marker.on('click', () => {
                if (index % 2 === 0) {
                  this.initPlayer(camera.video_address, camera.serial_number);
                } else {
                  this.initPlayer1(camera.video_address, camera.serial_number);
                }
              });

              this.map.add(marker);
            }
          });
        }


      })
    },
    async getEquipmentType(local, base_id) {
      let type = '水质检测' // 默认类型
      await caicon({ zuobiao: local, base_id: base_id }).then(res => {
        if (res && res.data) {
          type = res.data
        }
      })
      return type
    },

    setCustomLabelStyle(marker, equipmentType, index) {
      // 使用 setTimeout 来确保 DOM 已经更新
      console.log("labelDom", marker, equipmentType, index);
      const findLabel = () => {
        const labelDom = document.querySelector(`.amap-marker-label .custom-label-${index}`);
        if (labelDom) {

          // labelDom.classList.remove('water-quality-label', 'meteorological-label');
          if (equipmentType === '水质检测') {
            labelDom.classList.add('water-quality-label');
          } else if (equipmentType === '气象检测') {
            labelDom.classList.add('meteorological-label');
          }
          return true;
        }
        return false;
      };

      // 如果直接查找失败，则开始轮询
      if (!findLabel()) {
        let attempts = 0;
        const interval = setInterval(() => {
          if (findLabel() || attempts >= 10) {
            clearInterval(interval);
          }
          attempts++;
        }, 300);
      }
    },
    onCloseCover() {
      this.box = 0;
    },
    initPlayer(url, SerialNumber) {
      if (!SerialNumber || !this.jktokens.value) {
        console.error('设备序列号或访问令牌未设置');
        return;
      }
      this.player = new EZUIKit.EZUIKitPlayer({
        id: 'video-container',
        accessToken: this.jktokens.value,
        url: url,
        height: '220',
        width: '450',
        template: 'e33cecdfc3bb4019a06591a15cda2b1f',
        autoplay: true,  // 自动播放
        footer: ['fullScreen'], 
        handleError: (e) => {  // 添加错误处理
          console.error('播放器错误:', e);
        }
      });
    },
    initPlayer1(url, SerialNumber) {
      if (!SerialNumber || !this.jktokens.value) {
        console.error('设备序列号或访问令牌未设置');
        return;
      }
      this.player1 = new EZUIKit.EZUIKitPlayer({
        id: 'video-container1',
        accessToken: this.jktokens.value,
        url: url,
        height: '220',
        width: '450',
        template: 'e33cecdfc3bb4019a06591a15cda2b1f',
        autoplay: true,  // 自动播放
        handleError: (e) => {  // 添加错误处理
          console.error('播放器错误:', e);
        },
        // header: ['capturePicture', 'save', 'zoom'],  
        // footer: ['hd', 'fullScreen']  
      });
    },
    GetCamera() {
      this.base_id = this.$route.query.base_id
      getcamera({
        base_id: this.base_id,
      }).then(res => {
        this.cameralist = res.item_list;
        const videoAddresses = this.cameralist.map(camera => camera.video_address);
        const SerialNumber = this.cameralist.map(camera => camera.serial_number);
        this.videoAddresses = videoAddresses;
        this.SerialNumber = SerialNumber;
        console.log('视频地址数组:', res);
        if (this.cameralist.length > 0) {
          this.shebeilist.monitoring = this.cameralist;
        }

        // this.initPlayer(this.cameralist[0].video_address, this.SerialNumber[0]);
        // this.initPlayer1(this.cameralist[1].video_address, this.SerialNumber[1]);
      })

    },
    async getToken() {
      try {
        const appKey = '3d0be5dc16b846e58ba2e4efb80d6d7f'; // 替换为你的appKey  
        const appSecret = '1d040ec6b1a4d12061fa97ef21987942'; // 替换为你的appSecret  

        const response = await axios.post('https://open.ys7.com/api/lapp/token/get',
          `appKey=${appKey}&appSecret=${appSecret}`,
          {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          }
        );
        // 处理响应数据  
        this.jktokens.value = response.data.data.accessToken;
        console.log('shuju:', response.data.data.accessToken); // 这里你应该会看到返回的token数据（如果请求成功的话）  
        //  this.jktokens=response.data.accessToken;
      } catch (error) {
        // 错误处理  
        console.error('获取Token失败:', error);
      }
    },
   GetWeather () {
      // 获取 base_id 参数（如果有的话，可以根据需求传入）
      getweather({
        city: this.city,
      }).then(res => {
        this.livetianqi = {
        temperature: res.temperature,  // 温度
        humidity: res.humidity,        // 湿度
        wind_direction: res.wind_direction, // 风向
        wind_power: res.wind_power,     // 风力    
        guangzhao: res.guangzhao, //光照
        precipitation: res.precipitation,   // 降水量
        pressure: res.pressure ,       // 气压
         };
         Object.keys(this.livetianqi).forEach(key => {
          if (Object.prototype.hasOwnProperty.call(this.wetherinfo1, key)) {
            this.wetherinfo1[key].value = this.livetianqi[key];  // 更新value字段
          }
        });
        console.log(this.wetherinfo1);
       })
       .catch(error => {
          // 处理错误并显示错误消息
          console.error('获取天气数据失败:', error);
          this.errorMessage = '获取天气数据失败，请稍后再试。';  // 清除已有的天气数据
        });
    }

  }

}
</script>
<template>

  <div class="w-100 h-100 d-flex flex-column  ">

    <div class="w-100 h-100 map-container position-absolute " id="map-container"></div>
    <img src="@/assets/ui/bg.png" alt="" class="w-100 h-100 position-absolute top-0 left-0"
      style="pointer-events: none;">
    <div v-if="box === 1" class="equip-box"
      :style="{ backgroundImage: `url(${backgroundImage})`, height: this.miaoshuFormatted.length > 12 ? '20rem' : '20rem' }">
      <!-- <img src="@/assets/ui/prompt.png" alt=""> -->
      <div class="text">
        <div class="info-table">
          <div v-for="(item, index) in miaoshuFormatted" :key="index"
            :class="['info-row', { 'full-width': index < 3 }]">
            <div class="info-label"><span :style="{ color: labelcolor }">{{ item.label }}</span></div>
            <div class="info-value"><span :style="{ color: valuecolor }">{{ item.value }}</span></div>
          </div>
        </div>
      </div>
      <div class="close-icon d-flex align-items-center justify-content-center" @click="onCloseCover">
        <svg t="1639825855503" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
          p-id="26567" width="1rem" height="1rem">
          <path
            d="M846.005097 957.24155c-28.587082 0-57.174164-10.911514-78.996169-32.733519L96.632851 254.131955c-43.644009-43.644009-43.644009-114.348328 0-157.992337s114.348328-43.644009 157.992337 0L925.001265 766.515694c43.644009 43.644009 43.644009 114.348328 0 157.992337C903.17926 946.330036 874.592179 957.24155 846.005097 957.24155z"
            p-id="26568" fill="#ffffff"></path>
          <path
            d="M175.62902 957.24155c-28.587082 0-57.174164-10.911514-78.996169-32.733519-43.644009-43.644009-43.644009-114.348328 0-157.992337L767.008928 96.139617c43.644009-43.644009 114.348328-43.644009 157.992337 0s43.644009 114.348328 0 157.992337L254.625188 924.508032C232.803183 946.330036 204.216101 957.24155 175.62902 957.24155z"
            p-id="26569" fill="#ffffff"></path>
        </svg>
      </div>
    </div>
    <div class="header">
      <Head2 :isShow="true"></Head2>
    </div>
    <div class="main d-flex flex-row  ">
      <div class="home-sidebar  ">
        <div style="height: 64.8%;">
          <SubtitledSection title="船舶列表">
            <template>
              <DeviceList :shebeilist="shebeilist" @link-shebei="handleLinkShebei"></DeviceList>
            </template>
          </SubtitledSection>
        </div>
        <div style="height: 32.6%; ">
          <SubtitledSection title="报警信息">
            <template>
              <AlarmList :baselist="alertYuanList"></AlarmList>
            </template>
          </SubtitledSection>
        </div>

      </div>
      <div class="home-center">
        <div class="info-box">
          <div v-for="(item, i) in wetherinfo1" :key="i" class="info-item"
            :style="{ backgroundImage: 'url(' + require(`@/assets/ui/${item.img}`) + ')' }">
            <div style=" margin-left: 3.4rem;">
              {{ item.value }}
            </div>
          </div>
        </div>
        <div class="bottom-box ">
          <div style="width:49.5% ;">
            <SubtitledSectionLong title="设备监控">
              <template>
                <div class="video-wrapper">
                  <div id="video-container" class="video-content">
                    <img src="../assets/img/jiankong(2).png" alt="视频占位图">
                  </div>
                </div>
              </template>
            </SubtitledSectionLong>
          </div>
          <div style="width: 49.5%;margin-left: 0.6rem;">
            <SubtitledSectionLong title="设备监控">
              <template>
                <div class="video-wrapper">
                  <div id="video-container1" class="video-content">
                    <img src="../assets/img/jiankong(1).png" alt="视频占位图">
                  </div>
                </div>
              </template>
            </SubtitledSectionLong>
          </div>
        </div>
      </div>
      <div class="home-sidebar ">
        <div style="height: 100%;">
          <SubtitledSection title="设备参数" style="pointer-events: auto;">
            <template>
              <div class="h-100 w-100">
                <div class="w-100 " style="height: 15px;">
                  <el-row type="flex" align="middle" justify="center">
                    <el-col :span="24">
                      <div class="time-container">
                        <i class="el-icon-time"></i>
                        <span style="margin-left: 10px;">{{ currentTime }}</span>
                      </div>
                    </el-col>
                  </el-row>
                </div>
                <div class="w-100 right-item1">
                  <div class="right-item1-bg">
                    <div>
                      <div>{{ this.TEM }}</div>
                      <div>温度</div>
                    </div>
                    <div>
                      <div>{{ this.selectid == 1 ? this.PH : this.HUMIDITY }}</div>
                      <div>{{ this.selectid == 1 ? 'P H' : '湿度' }}</div>
                    </div>
                    <div>
                      <div>{{ this.selectid == 1 ? this.O2 : this.ATM }}</div>
                      <div>{{ this.selectid == 1 ? '含氧量' : '气压' }}</div>
                    </div>
                    <div>
                      <div>{{ this.selectid == 1 ? this.SALT : this.CON }}</div>
                      <div>{{ this.selectid == 1 ? '电导' : '雨量' }}</div>
                    </div>
                  </div>
                </div>
                <div class="w-100 right-item2" :class="this.selectid == 1 ? 'shebei1' : 'shebei2'">
                  <span>{{ this.selectid == 1 ? '水温' : '温度' }}</span>
                  <chartline v-if="lineData && lineData.length > 0 && lineData[0]" :Data="lineData[0]"></chartline>
                </div>
                <div class="w-100 right-item2" :class="this.selectid == 1 ? 'shebei1' : 'shebei2'">
                  <span>{{ this.selectid == 1 ? 'PH' : '湿度' }}</span>
                  <chartline v-if="lineData && lineData.length > 0 && lineData[1]" :Data="lineData[1]"></chartline>
                </div>
                <div class="w-100 right-item2" :class="this.selectid == 1 ? 'shebei1' : 'shebei2'">
                  <span>{{ this.selectid == 1 ? '含氧量' : '气压' }}</span>
                  <chartline v-if="lineData && lineData.length > 0 && lineData[2]" :Data="lineData[2]"></chartline>
                </div>
                <!-- <div class="w-100 right-item2" :class="this.selectid == 1 ? 'shebei1' : 'shebei2'" v-if="this.selectid == 2">
                  <span>雨量</span>
                  <chartline v-if="lineData && lineData.length > 0 && lineData[3]" :Data="lineData[3]"></chartline>
                </div> -->
              </div>
            </template>
          </SubtitledSection>
        </div>
      </div>
    </div>
  </div>

</template>


<style lang="less" scoped>
::v-deep .camera-label {
  background-image: url('~@/assets/ui/position-text-bg1.png');
  /* 摄像头标签背景 */
  background-size: 100% 100%;
  background-repeat: no-repeat;
  color: #FFFFFF;
  font-family: PingFang SC;
  font-weight: 600;
  font-size: 18px;
}

.time-container {
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #6C8CBC;
  line-height: 15px;
}

/deep/ .amap-icon {
  cursor: pointer !important;
  pointer-events: auto !important;
}

.video-wrapper {
  pointer-events: auto;
  width: calc(100% - 2.6rem);
  height: calc(100% - 2.6rem);
  padding: 0.5rem 1.3rem 1.3rem 1.3rem;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.video-content {
  width: 100%;
  height: 100%;
  object-fit: contain;
  max-width: 100%;
  max-height: 100%;
}

.right-item1-bg {
  width: 100%;
  height: 100%;
  background-image: url('~@/assets/ui/water_quality.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  gap: 5px 90px; // 如果您想在四个部分之间添加一些间距

  >div {

    display: flex;
    flex-direction: column;
    justify-content: center;

    div:first-child {
      height: 30%;
      text-align: center;
      font-family: PingFang SC;
      font-weight: 600;
      font-size: 18px;
      color: #FFFFFF;
    }

    div:last-child {
      height: 30%;
      text-align: center;
      font-family: PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: #6C8CBC;
    }
  }
}

.right-item1 {
  padding: 2px 0 2px 0;
  height: calc(20% - 4px);
}

.shebei1 {
  height: calc(26.5% - 12px);
}

.shebei2 {
  height: calc(26.5% - 8px);
}

.right-item2 {
  // border: 1px red solid;
  padding: 4px 0 4px 0;
  font-family: Source Han Sans CN;
  font-weight: 800;
  font-size: 18px;
  color: #FFFFFF;
  display: flex;
  flex-direction: column;

  span {
    flex: 0 0;
    line-height: 18px;
  }

  div {
    flex: 1 1;
  }
}

::v-deep .amap-marker-label {
  border: 0;
  background-color: transparent;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  font-family: PingFang SC;
  font-weight: 600;
  font-size: 18px;
  color: #FFFFFF;
  // line-height: 41px;
  text-stroke: 1px #000000;
  -webkit-text-stroke: 1px #000000;
}

::v-deep .water-quality-label {
  background-image: url('~@/assets/ui/position-text-bg.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

::v-deep .meteorological-label {
  background-image: url('~@/assets/ui/position-text-bg2.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

// /deep/.amap-marker-label {
//   border: 0;
//   background-color: rgba(54, 74, 112, 0.4);
//   padding: 10px;
//   // background-image: url('~@/assets/ui/position-text-bg.png');
//   background-size: 100% 100%;
//   background-repeat: no-repeat;
//   font-family: PingFang SC;
//   font-weight: 600;
//   font-size: 18px;
//   color: #FFFFFF;
//   // line-height: 41px;
//   text-stroke: 1px #000000;

//   -webkit-text-stroke: 1px #000000;
// }


//  地图设备提示框样式
.equip-box {
  position: absolute;
  top: 43%;
  /* 改为 50% */
  left: 50%;
  transform: translate(-50%, -50%);
  /* 添加这行，使元素居中 */
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 16px;
  // color: #F4ECC4;
  line-height: 32px;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  width: 25rem;
  // height: 18rem;


  // img {
  //   width: 22.2rem;
  // }

  .text {
    position: absolute;
    top: 0;
    left: 0;
    padding: 1rem 1rem;
  }


  .info-table {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
  }

  .info-row {
    display: flex;
    width: 50%;
    margin-bottom: 0.5rem;

    &.full-width {
      width: 100%;
    }
  }

  .info-label {
    width: 5rem; // 设置固定宽度，可以根据需要调整
    margin-right: 0.5rem;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: space-between;
    white-space: nowrap;
    overflow: hidden;

    &::after {
      content: ':';
      margin-left: 0.2rem;
    }
  }

  .info-label span {
    display: inline-block;
    width: 100%;
    text-align: justify;
    text-align-last: justify;
    letter-spacing: 0.1em; // 调整字间距以实现等距效果

    font-family: PingFang SC;
    font-weight: 400;
    font-size: 17px;

    &::after {
      content: '';
      display: inline-block;
      width: 100%;
    }
  }

  .info-value {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

    font-family: PingFang SC;
    font-weight: 400;
    font-size: 17px;
    // color: #5CA0B1;//#c6e1e7
    // line-height: 28px;
  }

  .close-icon {
    position: absolute;
    top: -2.5rem;
    right: 0rem;
    width: 2.4rem;
    height: 2.4rem;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 0.3rem;
  }

  /*item框的高度*/
  .h-35 {
    height: 35%;
  }

  /*左下角设备描述字体*/

}

.header {
  width: 100%;
  height: 6rem;
}

.main {
  width: calc(100% - 2.7rem);
  height: calc(100% - 8.7rem);
  padding: 1.35rem;
  color: black;
  position: relative;
  pointer-events: none;

}

.home-sidebar {
  pointer-events: auto;
  height: 100%;
  // height: calc(100vh-11.4rem);
  width: 22.5%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  div {
    width: 100%;
  }

}

.home-center {
  height: 100%;
  width: 55%;
  position: relative;
  padding-left: 0.5rem;
  padding-right: 0.5rem;
  pointer-events: none;
}

.info-box {
  margin-top: 1.6rem;
  height: 5%;
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.info-item {
  width: 12%;
  height: 100%;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  // justify-content: flex-end;
  align-items: center;
  font-family: PingFang SC;
  font-weight: 600;
  font-size: 20px;
  color: #FFFFFF;
  line-height: 41px;
}


.bottom-box {
  height: 32.6%;
  width: calc(100% - 1rem);
  margin-top: 1.5rem;
  position: absolute;
  display: flex;
  flex-direction: row;
  bottom: 0;

}

.box {
  background-image: url("~@/assets/ui/bg.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
}
</style>
